今天看见一个题目
1 | alert(1&&2) |
初始觉得结果可能是true
吧,任务逻辑运算符的返回值都是 true
或 false
,但结果是 2
。
对 2
这个结果并不是很明白,翻了下 ECMA spec
>
- Let lref be the result of evaluating LogicalANDExpression.
- Let lval be GetValue(lref).
- Let lbool be ToBoolean(lval).
- ReturnIfAbrupt(lbool).
- If lbool is false, return lval.
- Let rref be the result of evaluating BitwiseORExpression.
- Return GetValue(rref).
第一个表达式值的bool值为false,则返回第一个表达式的值。否则返回第二个表达式的值。
因此可以发现下面几种结果很好理解了。
1 | alert(false && 2) // false |
||
同理